import 'package:flutter/material.dart';
import 'package:device_util/device_util.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  Map<String, dynamic> _deviceInfo = {};
  final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformVersion = await DeviceUtil.getPlatformVersion() ?? 'Unknown platform version';
    } catch (e) {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  Future<void> _getDeviceInfo() async {
    try {
      // Initialize OAID SDK (Android only)
      await DeviceUtil.initOaidSdk();

      final deviceInfo = <String, dynamic>{};
      
      // Device Information
      deviceInfo['Android ID'] = await DeviceUtil.getAndroidId();
      deviceInfo['MAC Address'] = await DeviceUtil.getMacAddress();
      deviceInfo['Unique Device ID'] = await DeviceUtil.getUniqueDeviceId();
      deviceInfo['Device Type'] = await DeviceUtil.getDeviceType();
      deviceInfo['SDK Version'] = await DeviceUtil.getSdkVersion();
      
      // App Information
      deviceInfo['App Version'] = await DeviceUtil.getAppVersion();
      deviceInfo['App Version Code'] = await DeviceUtil.getAppVersionCode();
      deviceInfo['App Name'] = await DeviceUtil.getAppName();
      deviceInfo['Source Directory'] = await DeviceUtil.getSourceDir();
      
      // Network Information
      deviceInfo['IP Address'] = await DeviceUtil.getIpAddress();
      
      // Advertising Identifiers
      deviceInfo['OAID'] = await DeviceUtil.getOaid();
      deviceInfo['IDFA'] = await DeviceUtil.getIdfa();
      
      // Channel Information
      deviceInfo['Hume Channel'] = await DeviceUtil.getHumeChannel();
      deviceInfo['Tencent Channel'] = await DeviceUtil.getTencentChannel();
      deviceInfo['KS Channel'] = await DeviceUtil.getKsChannel();
      
      // Screen Metrics
      deviceInfo['Screen Metrics'] = await DeviceUtil.getMetrics();
      
      // Meta Data (example)
      deviceInfo['Meta Data (version_name)'] = await DeviceUtil.getAndroidMetaValue('version_name');
      
      setState(() {
        _deviceInfo = deviceInfo;
      });
    } catch (e) {
      if (mounted) {
        _scaffoldMessengerKey.currentState?.showSnackBar(
          SnackBar(content: Text('Error getting device info: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      scaffoldMessengerKey: _scaffoldMessengerKey,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Device Util Example'),
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        ),
        body: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text('Running on: $_platformVersion\n'),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: _getDeviceInfo,
                child: const Text('Get Device Information'),
              ),
              const SizedBox(height: 16),
              if (_deviceInfo.isNotEmpty) ...[
                const Text(
                  'Device Information:',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                ...(_deviceInfo.entries.map((entry) => Padding(
                  padding: const EdgeInsets.symmetric(vertical: 4.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '${entry.key}:',
                        style: const TextStyle(fontWeight: FontWeight.w600),
                      ),
                      Text(
                        '${entry.value}',
                        style: const TextStyle(fontSize: 12),
                      ),
                      const Divider(),
                    ],
                  ),
                ))),
              ],
            ],
          ),
        ),
      ),
    );
  }
}
